<?php
namespace plugin\entity_manager\src\config;

/**
 * The MIT License
 *
 * Copyright (c) <year> <copyright holders>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author Damiano Ciarla
 * @package plugin
 * @subpackage entity_manager/class/config
 */
class EntityManagerConfig
{
	const DEFAULT_CONNECTION_NAME = "plugin_entity_manager";
	
	/**
	 * Nome della cartella dove saranno generati e contenuti i model
	 *
	 * @var string
	 */
	private $_folderModel = "model";

	/**
	 * Istanza della libreria per la gestione della connessione al database
	 *
	 * @var \bxd\lib\db\Db
	 */
	private $_db;

	/**
	 * Configurazione della libreria per la gestione del database
	 *
	 * @var \bxd\lib\db\config\DbConfig
	 */
	private $_dbConfig;

	public function __construct()
	{
		$this->_db = \bxd\lib\db\Db::getInstance();
		spl_autoload_register(array($this, "_autoloadModel"));
	}

	/**
	 * Metodo che imposta o restituisce il nome della cartella dove sono contenute
	 * le entity generate
	 *
	 * @param string $folderName Nome della cartella dove sono contenute le entity
	 *
	 * @return string
	 */
	public function folderModel($folderName = null)
	{
		if($folderName === null)
			return $this->_folderModel;

		$this->_folderModel = $folderName;
	}

	/**
	 * Metodo che comunica al plugin di usare una connessione precedentemente creata
	 * impostandola come predefinita del progetto
	 *
	 * @param string $connectionName Nome della connessione
	 */
	public function useKnownConnection($connectionName)
	{
		if(!$this->_db->checkIfExistsConnection($connectionName))
			throw new Exception;
		
		$this->_dbConfig = $this->_db->getConfigByName($connectionName);
	}

	/**
	 * Metodo che imposta una connessione di collegamento al database direttamente riferendosi
	 * alla connessione della libreria Db
	 *
	 * @param \bxd\lib\db\config\DbConfig $dbConfig Configurazione della connessione al database
	 */
	public function useLibDbConfig(\bxd\lib\db\config\DbConfig $dbConfig)
	{
		$this->_db->addConnect($dbConfig);
		$this->_dbConfig = $dbConfig;
	}

	/**
	 * Metodo che comunica al plugin di creare una nuova connessione impostandola
	 * come predefinita del progetto
	 *
	 * @param string $host Host dove risiede il database
	 * @param string $username Username per accedere al database
	 * @param string $password Password per accedere al database
	 * @param string $dbname Nome del database
	 * @param string $connectionName Nome della connessione
	 */
	public function useNewConnection($host, $username, $password, $dbname, $connectionName = null)
	{
		$dbConfig = new \bxd\lib\db\config\DbConfig();
		$dbConfig->connectionName = (($connectionName === null) ? self::DEFAULT_CONNECTION_NAME : $connectionName);
		$dbConfig->host = $host;
		$dbConfig->username = $username;
		$dbConfig->passwd = $password;
		$dbConfig->dbname = $dbname;
		$dbConfig->type = "mysql";
		$dbConfig->persistent = false;
		$dbConfig->collate = "utf8_unicode_ci";
		$dbConfig->charset = "utf8";
		
		$this->_db = \bxd\lib\db\Db::getInstance();
		$this->_db->addConnect($dbConfig);
		
		$this->_dbConfig = $dbConfig;
	}

	/**
	 * Configurazione della connessione al database
	 *
	 * @return \bxd\lib\db\config\DbConfig
	 */
	public function getDbConfig()
	{
		return $this->_dbConfig;
	}
	
	/**
	 * Metodo che ritorna l'istanza della libreria per la gestione del database
	 *
	 * @return \bxd\lib\db\Db
	 */
	public function getConnection()
	{
		$this->_db->connect($this->_dbConfig->connectionName);
		$this->_db->useConnection($this->_dbConfig->connectionName);

		return $this->_db;
	}

	private function _autoloadModel($className)
	{
		if(strpos($className, "\\") !== false)
		{
			$classNameToPart = explode("\\", $className);

			if($classNameToPart[0] == "")
				array_shift($classNameToPart);

			if($classNameToPart[0] == "entity_manager" && $classNameToPart[1] == "model")
			{
				$classPath = \Bxd::getInstance()->pathApplication . '/' . $this->_folderModel;
				
				if(count($classNameToPart) == 4 && $classNameToPart[2] == "base")
					$classPath .= '/' . $classNameToPart[2];
					
				$classPath .= '/' . end($classNameToPart) . '.php';

				if(file_exists($classPath))
				{
					include_once $classPath;
				}
				else
				{
					if(count($classNameToPart) == 3)
					{
						throw new \plugin\entity_manager\src\exception\EntityManagerException(array($className, $this->_folderModel), \plugin\entity_manager\src\exception\EntityManagerException::LOAD_ENTITY_EXTENDED_NOT_FOUND);
					}
					else
					{
						throw new \plugin\entity_manager\src\exception\EntityManagerException(array($className, $this->_folderModel . '/' . $classNameToPart[2]), \plugin\entity_manager\src\exception\EntityManagerException::LOAD_ENTITY_BASE_NOT_FOUND);
					}
				}
			}
		}
	}
}
?>
